package com.nova.bluetooth.ui.bluetoothDemo;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothGatt;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.dido.fastblelib.data.BleDevice;
import com.dido.fastblelib.exception.BleException;
import com.dido.fastblelib.utils.HexUtil;
import com.nova.bluetooth.R;
import com.nova.bluetooth.adapter.ScannedAdapter;
import com.nova.bluetooth.bean.AdvertisingField;
import com.nova.bluetooth.bean.DeviceConfigBean;
import com.nova.bluetooth.databinding.ActivityScanBleactivityBinding;
import com.nova.bluetooth.helpUtils.BluetoothDataUtil;
import com.nova.bluetooth.manage.BluetoothHelper;
import com.nova.bluetooth.widget.CommonDialog;
import com.nova.bluetooth.helpUtils.LogUtil;
import com.nova.bluetooth.helpUtils.MyGattCallback;
import com.nova.bluetooth.helpUtils.MyScanCallback;
import com.nova.bluetooth.helpUtils.ToastUtils;
import com.nova.bluetooth.permission.OnPermissionListener;
import com.nova.bluetooth.permission.PermissionManageActivity;
import com.nova.bluetooth.permission.PermissionType;

import java.util.List;

@SuppressLint("MissingInflatedId")
public class DemoScanBLEActivity extends PermissionManageActivity implements MyScanCallback, MyGattCallback {
    private static final String TAG = "ScanBLEActivity";
    public static final String DEVICE_CONFIG = "deviceConfig";
    private ScannedAdapter mAdapter;

    private ActivityScanBleactivityBinding binding;
    private DeviceConfigBean deviceConfigBean;

    // 添加 ProgressDialog 成员变量
    private ProgressDialog progressDialog;

    private void showProgressDialog() {
        // 显示 ProgressDialog
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    private void dismissProgressDialog() {
        // 隐藏 ProgressDialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityScanBleactivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initView();
        initData();
        setPaddingBottom(this,binding.getRoot());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothHelper.getInstance().cancelScan();
        BluetoothHelper.getInstance().cleanCallback();
    }

    private void goScanBle() {
        if (deviceConfigBean == null) {
            LogUtil.e(TAG + " deviceName is null");
            return;
        }

        getBluetoothPermission(new OnPermissionListener() {
            @Override
            public void onPermissionGranted(PermissionType permissionType) {
                BluetoothHelper.getInstance().startScanByDeviceName(deviceConfigBean.getDeviceName());
            }

            @Override
            public void onPermissionDenied(PermissionType permissionType) {

            }
        }, "获取蓝牙设备需要定位、发现附近设备权限");
    }

    private void initView() {
        binding.ivBack.setOnClickListener(v -> finish());
        binding.btnScan.setOnClickListener(v -> {
            mAdapter.getData().clear();
            goScanBle();
        });
        mAdapter = new ScannedAdapter();
        RecyclerView recyclerView = findViewById(R.id.recy_scanned);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);


        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                BluetoothHelper.getInstance().connect(mAdapter.getData().get(position));
            }
        });
        mAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                showOutputLogDialog(mAdapter.getData().get(position));
                return false;
            }
        });

        binding.llEmptyView.setVisibility(View.VISIBLE);
        binding.recyScanned.setVisibility(View.GONE);


        // 初始化 ProgressDialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在连接设备...");
        progressDialog.setCancelable(false);
    }

    private void initData() {
        BluetoothHelper.getInstance().setScanCallback(this);
        BluetoothHelper.getInstance().setGattCallback(this);
        deviceConfigBean = (DeviceConfigBean) getIntent().getSerializableExtra(DEVICE_CONFIG);
        goScanBle();
    }


    @SuppressLint("SetTextI18n")
    private void showOutputLogDialog(BleDevice bleDevice) {
        View v = getLayoutInflater().inflate(R.layout.dialog_bluetooth_ad, null);
        CommonDialog dialog = new CommonDialog(this, v);
        dialog.setWidth(R.dimen.dp_320);
        dialog.setCancelable(true);
        dialog.setGravity(Gravity.CENTER);
        dialog.showDialog();

        TextView adData = v.findViewById(R.id.tv_broadcast_data);
        adData.setText("0x" + HexUtil.encodeHexStr(bleDevice.getScanRecord()));
        List<AdvertisingField> advertisingFields = BluetoothDataUtil.parseAdvertisingData(bleDevice.getScanRecord());
        byte[] data_01 = getDataByType(0x01, advertisingFields);
        byte[] data_16 = getDataByType(0x16, advertisingFields);
        byte[] data_ff = getDataByType(0xff, advertisingFields);

        //test
//        String testData = "ffff006400640063000001010203040506ffffffffffff0000000000";
//        data_ff = HexUtil.hexStringToBytes(testData);

        TextView tv_type_data = v.findViewById(R.id.tv_type_data);
        for (AdvertisingField advertisingField : advertisingFields) {
            tv_type_data.append(advertisingField.toString() + "\n");
        }

        TextView tv_version_code_1 = v.findViewById(R.id.tv_version_code_1);
//        TextView tv_version_code_2 = v.findViewById(R.id.tv_version_code_2);
//        TextView tv_version_code_3 = v.findViewById(R.id.tv_version_code_3);

        TextView tv_device_type = v.findViewById(R.id.tv_device_type);
//        TextView tv_sn = v.findViewById(R.id.tv_sn);
        TextView tv_device_ble_mac = v.findViewById(R.id.tv_device_ble_mac);
        TextView tv_device_bt_mac = v.findViewById(R.id.tv_device_bt_mac);

        tv_version_code_1.setText("软件版本号：" + BluetoothDataUtil.getVersionFromData(data_ff));
//        tv_version_code_2.setText("固件版本号：" + BluetoothDataUtil.getFirmwareVersionFromData(data_ff));
//        tv_version_code_3.setText("硬件版本号：" + BluetoothDataUtil.getHardwareVersionFromData(data_ff));
        tv_device_type.setText("DeviceType：" + BluetoothDataUtil.getDeviceTypeFromData(data_ff));
//        tv_sn.setText("SN：" + BluetoothDataUtil.getSerialNumberFromData(data_ff));
        tv_device_ble_mac.setText("BLE MAC：" + BluetoothDataUtil.getBLEMacFromData(data_ff));
        tv_device_bt_mac.setText("BT MAC：" + BluetoothDataUtil.getBTMacFromData(data_ff));
    }

    private byte[] getDataByType(int type, List<AdvertisingField> advertisingFields) {
        for (AdvertisingField advertisingField : advertisingFields) {
            if (advertisingField.getType() == type) {
                return advertisingField.getData();
            }
        }
        return null;
    }

    @Override
    public void onScanStarted() {
        binding.btnScan.setText("开始扫描");
        binding.btnScan.setClickable(false);
    }

    @Override
    public void onScanning(BleDevice bleDevice) {
        binding.btnScan.setText("扫描中...");
        mAdapter.addData(bleDevice);

        binding.llEmptyView.setVisibility(View.GONE);
        binding.recyScanned.setVisibility(View.VISIBLE);
        binding.tvTips.setVisibility(View.VISIBLE);
    }

    @Override
    public void onScanFinished(List<BleDevice> scanResultList) {
        binding.btnScan.setText("重新扫描");
        binding.btnScan.setClickable(true);


    }

    @Override
    public void onStartConnect() {
        showProgressDialog();
    }

    @Override
    public void onConnectFail(BleDevice bleDevice, BleException exception) {
        dismissProgressDialog();
        ToastUtils.show("连接失败:" + exception.toString());
    }

    @Override
    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {

    }

    @Override
    public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {

    }

    @Override
    public void onConnectedNotifySuccess(BleDevice bleDevice) {
        dismissProgressDialog();
        Intent intent = new Intent(DemoScanBLEActivity.this, DemoBluetoothControlActivity.class);
        intent.putExtra(DemoScanBLEActivity.DEVICE_CONFIG, deviceConfigBean);
        startActivity(intent);
        finish();
    }
}